package org.graph;

import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.StringTokenizer;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

/**
 * Contains some generic graphical tasks.
 *
 * @author See <a href="the Google Code page of the easy-utils
 * library">http://code.google.com/p/easy-utils/</a> for collaborators and other
 * information.
 */
public abstract class GraphTasks {

    /**
     * Takes a screenshot not including the mouse pixels.
     *
     * @param storeAs {@link Path} The path to save the file to. If
     * <value>null</value>, the given path already exists or any IO error
     * happens, the image is not saved as a file but it's returned anyway.
     * @return {@link ImageIcon} The screenshot.
     */
    public static ImageIcon takeScreenshot(Path storeAs) {
        BufferedImage capture = null;

        try {
            capture = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        } catch (AWTException ex) {
            System.err.println("There was an error when trying to take a screenshot - " + ex.getMessage());
        }

        if (storeAs != null && !Files.exists(storeAs)) {
            try {
                Files.createFile(storeAs);
            } catch (IOException ex) {
                System.err.println("Couldn't create file to store image because of an IOError - " + ex.getMessage());
            }
            String informalFormatName;
            for (StringTokenizer tokenizer = new StringTokenizer(storeAs.toFile().getName(), ".");;) {
                informalFormatName = tokenizer.nextToken();
                if (!tokenizer.hasMoreTokens()) {
                    break;
                }
            }
            try {
                ImageIO.write(capture, informalFormatName, storeAs.toFile());
            } catch (IOException ex) {
                System.err.println("The image couldn't be saved as a file because of an IOError - " + ex.getMessage());
            }
        }

        return new ImageIcon(capture);
    }
}
